#include <fstream>
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>
#include "Parser.h"
#include "Entities/Book.h"


Parser::Parser() {
}

Book* Parser::parseBook(string* path) {

	string filePath = *path;
	char* fPath = &filePath[0];
	string* bookData = new string[3];
	fstream file;
	file.open(fPath, ios::in);

	filePath = ExtractFilename(path);

	if (file) {

		unsigned int numElements = 0;

		//count number of elements
		unsigned int i = 0;
		while (i < filePath.size()) {
			if (filePath[i] == '-')
				numElements++;
			i++;
		}

		//parse the path
		i = 0;
		unsigned int j = 0;
		while (i < numElements + 1) {

			while (filePath[j] != '-' && filePath[j] != '.') {
				if ((filePath[j] != ' ') || (filePath[j + 1] != '-')) {
					bookData[i] = bookData[i] + filePath[j];
				}
				j++;
			}

			j = j + 2;
			i++;
		}

		//setting the book data
		Book* book = new Book();
		book->setAuthor(bookData);
		book->setTitle(bookData + 1);

		if (numElements == 2) {
			book->setPublisher(bookData + 2);
		} else {
			*(bookData + 2) = "Not Defined";
			book->setPublisher(bookData + 2);
		}

		//parsing text words
		string word;
		while (file >> word) {
			eraseSymbols(word);
			if (word.length() > 3) {
				if (!isStopWord(word)) {
					book->addWord(word);
				}
			}
		}
		file.close();

		delete[] bookData;

		return book;
	} else {
		cout << "File not Found" << endl;
		return NULL;
	}

}

string Parser::ExtractFilename(string* path) {
	return (*path).substr((*path).find_last_of('/') + 1);
}

void Parser::eraseSymbols(string & s) {
	fstream pathEraseSymbol;
	pathEraseSymbol.open("/home/maruuchis/eraseSymbol.txt", ios::in);
	char cadena;
	while (!pathEraseSymbol.eof()) {
		pathEraseSymbol >> cadena;
		s.erase(std::remove(s.begin(), s.end(), cadena), s.end());
	}
	pathEraseSymbol.close();
}

bool Parser::isStopWord(string word) {
	fstream pathStopWord;
	pathStopWord.open("/home/maruuchis/stopWord.txt", ios::in);
	string cadena;
	while (!pathStopWord.eof()){
		pathStopWord >> cadena;
		if (word == cadena){
			return true;
			pathStopWord.close();
			break;
		}
	}
	pathStopWord.close();
	return false;
}


Parser::~Parser() {
}
